package com.sxt.sys.controller;

import com.sxt.sys.constant.SYSConstant;
import com.sxt.sys.domain.Operator;
import com.sxt.sys.service.OperatorService;
import com.sxt.sys.utils.WebUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 登陆控制器
 * @author WanMing
 * @date 2019/1/31 10:13
 */

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private OperatorService operatorService;

    /**
     * 跳转到登陆页面
     * @return
     */
    @RequestMapping("toLogin")
    public String toLogin(){
        return "main/login";
    }

    /**
     * shiro处理用户的登录的请求
     * @param operatorName
     * @param operatorPwd
     * @param model
     */
    @RequestMapping("login")
    public String login(String operatorName,String operatorPwd,Model model){

        //获取当前线程的subject对象
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(operatorName,operatorPwd);

        //认证用户
        try {
            //使用subject去执行认证
            subject.login(token);
            System.out.println("登陆成功");
            //存入session域
            Operator operator = (Operator) subject.getPrincipal();
            WebUtils.getCurrentSession().setAttribute("operator",operator);
            return "main/main";
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码不正确");
            model.addAttribute(SYSConstant.LOGIN_ERROR_MSG,SYSConstant.PASSWORD_ERROR);
        }catch (UnknownAccountException e) {
            System.out.println("用户不存在");
            model.addAttribute(SYSConstant.LOGIN_ERROR_MSG,SYSConstant.USERNAME_ERROR);
        }
        return "main/login";

    }

    /**
     * 加载主页的内敛info页面
     * @return
     */
    @RequestMapping("info")
    public String loadInfo(){
        return "main/info";
    }
}
